package com.example.touch.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.touch.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class SignatureView extends View {
    public static final String TAG = "asdf";
    private Path mPath = new Path();
    private Path mPath2 = new Path();
    private Paint mPaint = new Paint();
    //定位两个手指
    private float x1, x2, y1, y2;
    private boolean isDrawing = false;
    //位图的绘制内容输出者：画布
    private Canvas mCanvas;
    //用来存放绘制内容的位图
    private Bitmap mCacheBitmap;
    //上下文
    private Context mContext;

    public SignatureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(getResources().getColor(R.color.red, null));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCacheBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mCacheBitmap);
        mCanvas.drawColor(Color.WHITE);
    }

//    @SuppressLint("ClickableViewAccessibility")
//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                mPath.moveTo(event.getX(), event.getY());
//                Log.e(TAG, "ACTION_DOWN getX = " + event.getX() + " getY = " + event.getY());
//                break;
//            case MotionEvent.ACTION_MOVE:
//                mPath.lineTo(event.getX(), event.getY());
//                Log.e(TAG, "ACTION_MOVE getX = " + event.getX() + " getY = " + event.getY());
//                break;
//            case MotionEvent.ACTION_UP:
//                Log.e(TAG, "ACTION_UP getX = " + event.getX() + " getY = " + event.getY());
//                break;
//        }
//        //真正负责绘制签名笔迹的画布，在这里接收路径mPath，以及事先定义好的颜料
//        mCanvas.drawPath(mPath, mPaint);
//        invalidate();
//        return true;
//    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x, y;
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                // 第一个手指按下，开始新的路径
                x = event.getX();
                y = event.getY();
                mPath.moveTo(x, y);
                isDrawing = true;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                // 第二个手指按下，开始第二个路径
                if (event.getPointerCount() == 2) {
                    int pointerIndex = event.getActionIndex();
                    x = event.getX(pointerIndex);
                    y = event.getY(pointerIndex);
                    mPath2.moveTo(x, y);
                }
                // 重置第一个路径的最后一个点，以便重新开始绘制
                x = event.getX(0);
                y = event.getY(0);
                mPath.lineTo(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                // 绘制两个手指的路径
                for (int i = 0; i < event.getPointerCount(); i++) {
                    x = event.getX(i);
                    y = event.getY(i);
                    if (i == 0) {
                        // 手指1移动
                        mPath.quadTo(x1, y1, x, y);
                    } else if (i == 1) {
                        // 手指2移动
                        mPath2.quadTo(x2, y2, x, y);
                    }
                }
                // 在mCacheBitmap上绘制两个路径
                mCanvas.drawPath(mPath, mPaint);
                mCanvas.drawPath(mPath2, mPaint);
                invalidate();
                break;
            case MotionEvent.ACTION_POINTER_UP:
                // 一个手指抬起，如果是第二个手指，则需要处理
                int pointerIndex = event.getActionIndex();
                if (pointerIndex == 1 && event.getPointerCount() == 1) {
                    x1 = event.getX(0);
                    y1 = event.getY(0);
                    // 重置第二个路径的最后一个点
                    mPath2.lineTo(x2, y2);
                }
                break;
            case MotionEvent.ACTION_UP:
                // 最后一个手指抬起，停止绘制
                isDrawing = false;
                break;
        }
        // 更新手指坐标
        x1 = event.getX(0);
        y1 = event.getY(0);
        if (event.getPointerCount() > 1) {
            x2 = event.getX(1);
            y2 = event.getY(1);
        }
        return true;
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e(TAG, "onDraw canvas = " + canvas);
        canvas.drawPath(mPath, mPaint);
        canvas.drawPath(mPath2, mPaint);
    }


    /**
     * 清空
     */
    public void clear() {
        Log.e(TAG, "clear()");
        if (mPath != null) {
            Log.e(TAG, "before clear mPath isEmpty => " + mPath.isEmpty());
            mPath.reset();
            mCanvas.drawColor(Color.WHITE);
            Log.e(TAG, "after clear mPath isEmpty => " + mPath.isEmpty());
            invalidate();
        }
        if (mPath2 != null) {
            Log.e(TAG, "before clear mPath isEmpty => " + mPath2.isEmpty());
            mPath2.reset();
            mCanvas.drawColor(Color.WHITE);
            Log.e(TAG, "after clear mPath isEmpty => " + mPath2.isEmpty());
            invalidate();
        }
    }

    public void save() {
        //创建一个文件用于存放图片
        File file = new File(mContext.getExternalFilesDir(null) + "testSign.png");
        if (file.exists()) {
            file.delete();
        }
        OutputStream outputStream = null;
        try {
            //输出到这个文件
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(mContext, "保存异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        //压缩形成输出流
        mCacheBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        Toast.makeText(mContext, "保存成功!path:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    }

    public void saveImageToGallery() {
        String savedImageURL = MediaStore.Images.Media.insertImage(
                mContext.getContentResolver(),
                mCacheBitmap,
                "testSign",
                "testSign save"
        );
        Toast.makeText(mContext, "保存成功! URL:" + savedImageURL, Toast.LENGTH_SHORT).show();
    }
}
